param([Switch] $cleanOnly)

$installUtil = "$env:SYSTEMROOT\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe"
$installUtil64 = "$env:SYSTEMROOT\Microsoft.NET\Framework64\v2.0.50727\InstallUtil.exe"
$installError = "Could not install the Cmdlet Designer snapin. For it first use, " +
      "the Cmdlet Designer must be first launched as an Administrator in order to register its snapin.`r`n`r`n" +
      "To launch the Cmdlet Designer as an administrator, first launch an elevated PowerShell window." +
      "Then, in that window, run the following commands:`r`n`r`n" +
      "Push-Location`r`n" +
      "Set-Location '$(Resolve-Path .)'`r`n" +
      ".\CmdletDesigner.exe`r`n" +
      "Pop-Location`r`n`r`n" +
      "These steps are only required for installation. The Cmdlet Designer does not otherwise require " +
      "administrative privileges."

if(-not $cleanOnly)
{
    ## Exit if we don't need to do an upgrade
    $snapin = Get-PsSnapin -reg PsSpecCmdletManagement -ErrorAction SilentlyContinue
    if($snapin.ModuleName -eq (Resolve-Path .\PsSpecCmdlets.dll).Path)
    {
        Write-Verbose "Skipping installation. Snapin is already present."
        return
    }
}

## Uninstall the 32-bit and 64-bit versions of the old snapin
Get-PsSnapin -reg AspenCmdletManagement -ErrorAction SilentlyContinue | 
    Foreach-Object {
        Write-Verbose "Uninstalling $($_.ModuleName)"
        & $installUtil -l -u $_.ModuleName > $null
        if(Test-Path $installUtil64) { & $installUtil64 -l -u $_.ModuleName > $null }
    }

## Uninstall the 32-bit and 64-bit versions of the new one
Get-PsSnapin -reg PsSpecCmdletManagement -ErrorAction SilentlyContinue | 
    Foreach-Object {
        Write-Verbose "Uninstalling $($_.ModuleName)"
        & $installUtil -l -u $_.ModuleName > $null
        if(Test-Path $installUtil64) { & $installUtil64 -l -u $_.ModuleName > $null }
    }

if(@(Get-PsSnapin -reg PsSpecCmdletManagement -ErrorAction SilentlyContinue).Count -gt 0)
{
    Write-Error $installError
}

if($cleanOnly)
{
    return
}

## Install the 32-bit and 64-bit versions
Write-Verbose "Installing $((Resolve-Path .\PsSpecCmdlets.dll).Path)"
& $installUtil -l -a .\PsSpecCmdlets.dll > $null
if(Test-Path $installUtil64) { & $installUtil64 -l -a .\PsSpecCmdlets.dll > $null }

if(@(Get-PsSnapin -reg PsSpecCmdletManagement -ErrorAction SilentlyContinue).Count -eq 0)
{
    Write-Error $installError
}